<?php

namespace Tool;

class CSV
{
	/**
	 * 导出CSV文件
	 */
	public static function download($filename, $header, $body)
	{
		// 1、字段与字段之间用逗号分隔开
		// 2、行与行之间需要换行符
		$fileData = collect([$header])
			->merge($body)
			->map(function ($item) {
				return self::utfToGbk(implode(',', $item));
			})
			->implode("\n");

		// 头信息设置
		header("Content-type:text/csv");
		header("Content-Disposition:attachment;filename=" . self::utfToGbk($filename . '.csv'));// 文件名
		header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
		header('Expires:0');
		header('Pragma:public');
		return $fileData;
	}

	// 存储CSV文件
	public static function save_csv_file($filename, $header, $body, $path = null)
	{
		$fileData = collect([$header])
			->merge($body)
			->map(function ($item) {
				try {
					return self::utfToGbk(implode(',', $item));
				} catch (\Exception $e) {
					dd([
						'保存文件错误',
						$item,
					]);
				}
			})
			->implode("\n");

		if (!$path) $path = app()->basePath('public/create_file/');
		$path = $path . $filename . '.csv';
		// 将一个字符串写入文件
		file_put_contents($path, $fileData);
		return $path;
	}

	private static function utfToGbk($str)
	{
		return mb_convert_encoding($str, 'GBK', 'UTF-8');
	}

}
